package l1j.opqlo.NewSystem.Extension;

import java.util.Timer;
import java.util.TimerTask;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.model.Getback;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.L1PcInventory;
import l1j.server.server.model.L1Teleport;
import l1j.server.server.model.Instance.L1DoorInstance;
import l1j.server.server.model.Instance.L1FieldObjectInstance;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1NpcInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_CharVisualUpdate;
import l1j.server.server.serverpackets.S_EffectLocation;
import l1j.server.server.serverpackets.S_GreenMessage;
import l1j.server.server.serverpackets.S_MapID;
import l1j.server.server.serverpackets.S_OtherCharPacks;
import l1j.server.server.serverpackets.S_OwnCharPack;
import l1j.server.server.serverpackets.S_PacketBoxGame;
import l1j.server.server.serverpackets.S_RedMessage;
import l1j.server.server.serverpackets.S_RemoveObject;
import l1j.server.server.serverpackets.S_SkillIconGFX;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.serverpackets.S_Weather;

public class Treasure1 {

	public class Treasure extends TimerTask {
		private final int _status;
		private final int _time;

		public Treasure(final int type, final int time) {

			this._status = type;
			this._time = time;
		}

		public void begin() {
			final Timer timer = new Timer();
			timer.schedule(this, this._time); // 延遲時間
		}

		@Override
		public void run() {

			switch (this._status) {
			case 1: // 傳送玩家入場
				final int[]xy = {32728, 32894, 32731, 32895};
				Treasure1.this.TelePort(xy);
				Treasure1.this.GreenMessage("副本將於10秒後開始，請在時間內擊殺怪物獲取【"+ Treasure1.this.itemname + "】來召喚出副本BOSS。", true, 10);
				Treasure1.this.StageMaster(2, 10); // 10秒後執行任務程序 2
				break;
			case 2:// 副本開始
				// spawn(2000034,1,32853,32867,(short) 5191,0,0,false); //BOSS
				// 出現位置

				Treasure1.this.GreenMessage("副本開始!!請擊殺怪物獲取【"+ Treasure1.this.itemname + "】來召喚出副本BOSS。", true,
						Treasure1.this._totaltime);

				for (int i = 0; i < Treasure1.this._npcId.length; i++) {
					TreasureMaster.getInstance().spawn(Treasure1.this._ItemId,
							Treasure1.this._npcId[i],
							Treasure1.this._npcCount[i],
							Treasure1.this._npcSpawnX[i],
							Treasure1.this._npcSpawnY[i],
							(short) Treasure1.this._mapid, 0, 0, false);
				}
				Treasure1.this.StageMaster(99, Treasure1.this._totaltime);
				// GameOver(_totaltime , true);

				break;
			case 3: // 觸發BOSS重生
				try {
					Treasure1.this.RedMessage("是誰這麼大膽...敢闖入我的地盤!?");
					for (final Object obj : L1World.getInstance().getVisibleObjects((short) Treasure1.this._mapid).values()) {
						// 刪除副本內的怪物
						if (obj instanceof L1NpcInstance) {
							final L1NpcInstance npc = (L1NpcInstance) obj;
							if (npc.getMaster() == null) {
								npc.deleteMe();
							}
						}
					}
					Thread.sleep(1000);
					Treasure1.this.StageMaster(4, 3); // 3秒後執行任務進程 4

				} catch (final InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;

			case 4:
//				int x = 32842,
//				y = 32854;
				final S_EffectLocation packet1 = new S_EffectLocation(32847,32863, 2483);
				for (final L1PcInstance ppc : Treasure1.this._pcParty) {
					if (ppc != null) {
//						if (y != 32857) {
//							y++;
//						} else {
//							y = 32854;
//							x -= 1;
//						}
//						L1Teleport.teleport(ppc, x, y,(short) Treasure1.this._mapid, 3, true);
						ppc.sendPackets(packet1);
					}
				}
				Treasure1.this.GreenMessage("請注意:10秒後...副本BOSS將出現在此地!", true,10);
				Treasure1.this.StageMaster(5, 10); // 3秒後執行任務進程 5

				break;

			case 5:// 副本頭目出現
				Treasure1.this.BossSet();
				Treasure1.this.GreenMessage("請在剩餘時間內擊殺BOSS!", true,(int) Treasure1.this.StageEnd.scheduledExecutionTime());
				break;
			case 99:
				Treasure1.this.resetTreasure(Treasure1.this._mapid);
				Treasure1.this.GreenMessage("副本結束，60秒後所有玩家將自動傳送離場。", true, 60);
				Treasure1.this.StageMaster(100, 60); // 60秒後執行任務程序 100 (
														// 傳送玩家離場，清除地上物品)

				TreasureMaster.getInstance().RemoveGameList(
						Treasure1.this._mapid); // 將此地圖設為可使用
				break;
			case 100:
				Treasure1.this.PcGoHome(Treasure1.this._mapid);
				break;
			}

			this.cancel();

		}

	}

	private L1PcInstance[] _pcParty;
	private final int _ItemId=77072026, _mapid, _totaltime=900; // opqlo 通關必須道具
	private final int[] _npcId={2000034},
			_npcCount={500}, _npcSpawnX={0}, _npcSpawnY={0};
	/** 0=X------1=Y------2=MaxX------3=MaxY */
	private final String itemname;

	private Treasure StageEnd;

	/**
	 * pc , mapid , xy[] , itemid , totaltime , npcid[] , npccount[] ,
	 * npcswawnX[] , npcswawnY[]
	 */
	public Treasure1(final L1PcInstance pc, final int mapid) {
		this._mapid = mapid;
		this.itemname = ItemTable.getInstance().findItemNameById(_ItemId);

		if (pc.isInParty()) {
			this._pcParty = pc.getParty().getMembers();
			this.GreenMessage("準備進入副本，10秒後將自動傳送。", true, 10);
			this.StageMaster(1, 10);// 10秒後 執行迴圈 1號
			/*
			 *
			 * if(party.isVacancy()){ pc.sendPackets(new
			 * S_SystemMessage("必須將隊伍組滿8人。"));
			 *
			 * }else if(!party.isLeader(pc)){ pc.sendPackets(new
			 * S_SystemMessage("你不是隊長。")); }else{ _pcParty = party.getMembers();
			 * for(final L1PcInstance MsgPc : _pcParty){ MsgPc.sendPackets(new
			 * S_SystemMessage("準備進入副本。")); } }
			 */
		} else {
			pc.sendPackets(new S_SystemMessage("你沒有組隊。"));
		}
	}

	private void BossSet() {
		TreasureMaster.getInstance().spawn(0, 45684, 1, 32847, 32863,(short) this._mapid, 0, 0, true);
//		final int npcid = 2000065;// 2000088 2000097 2000068
//		final int[][] loc = { { 32861, 32866 }, { 32861, 32867 },
//				{ 32861, 32868 }, { 32861, 32869 }, { 32853, 32881 },
//				{ 32852, 32881 }, { 32851, 32881 }, { 32850, 32881 },
//				{ 32849, 32881 }, { 32844, 32881 }, { 32843, 32881 },
//				{ 32842, 32881 }, { 32841, 32881 }, { 32851, 32851 },
//				{ 32850, 32851 }, { 32849, 32851 }, { 32848, 32851 },
//				{ 32847, 32851 }, { 32846, 32851 }, { 32825, 32845 },
//				{ 32825, 32846 }, { 32825, 32847 }, { 32825, 32848 },
//				{ 32825, 32849 }, { 32825, 32850 }, { 32825, 32851 },
//				{ 32825, 32852 }, { 32825, 32853 }, { 32835, 32871 },
//				{ 32834, 32871 }, { 32833, 32871 }, { 32832, 32871 },
//				{ 32831, 32871 }
//
//		};
//
//		for (final int[] element : loc) {
//			final L1NpcInstance npc = NpcTable.getInstance().newNpcInstance(npcid);
//			npc.setId(IdFactory.getInstance().nextId());
//			npc.setMap((short) this._mapid);
//			final int X = element[0];
//			final int Y = element[1];
//			npc.setX(X);
//			npc.setY(Y);
//			npc.setHomeX(X);
//			npc.setHomeY(Y);
//			npc.setHeading(0);
//			// npc.setPortalNumber(portalNumber);
//			final L1Map map = npc.getMap();
//			map.setPassable(X, Y, false);// 設定為不能走
//			L1World.getInstance().storeObject(npc);
//			L1World.getInstance().addVisibleObject(npc);
//		}

	}

	public void GameOver(final int time, final boolean isGamsTime) {
		if (!isGamsTime) {
			this.StageEnd.cancel();
		}

		this.StageEnd = new Treasure(99, time * 1000); // 整體副本時間
		this.StageEnd.begin();

	}

	/** 發送綠色訊息(是否含時間) **/
	private void GreenMessage(final String msg, final boolean haveTime,
			final int Time) {
		for (final L1PcInstance MsgPc : this._pcParty) {
			if (MsgPc != null) {
				MsgPc.sendPackets(new S_GreenMessage(msg));
				MsgPc.sendPackets(new S_SystemMessage(msg));
				if (haveTime && Time > 0) {
					MsgPc.sendPackets(new S_SkillIconGFX(71, Time));// opqlo
																	// 特殊地圖計時顯示
				}
			}
		}
	}

	private void PcGoHome(final int mapid) {
		// 將玩家傳出副本地圖
		for (final Object obj : L1World.getInstance()
				.getVisibleObjects((short) mapid).values()) {
			if (obj instanceof L1PcInstance) {
				final L1PcInstance pc = (L1PcInstance) obj;
				if (pc != null) {
					/** 刪除副本通關道具(禁止帶出) */
					final L1PcInventory inv = pc.getInventory();
					final L1ItemInstance item = inv.findItemId(this._ItemId);
					if (item != null) {
						pc.getInventory().removeItem(item);
					}

					if (pc.isDead()) {
						this.reStartPlayer(pc);
					} else {
						// 傳送至威頓村

						L1Teleport.teleport(pc, 33710, 32521, (short) 4,
								pc.getHeading(), true);
						// pc.sendPackets(new S_SkillIconGFX(71, 0));//opqlo
						// 特殊地圖計時顯示

						pc.sendPackets(new S_PacketBoxGame(S_PacketBoxGame.STARTTIMECLEAR));
					}
				}
			}// 刪除副本內的物品
			else if (obj instanceof L1Inventory) {
				final L1Inventory inventory = (L1Inventory) obj;
				inventory.clearItems();
			}
		}
	}

	/** 發送紅色訊息 **/
	private void RedMessage(final String msg) {
		for (final L1PcInstance MsgPc : this._pcParty) {
			if (MsgPc != null) {
				MsgPc.sendPackets(new S_RedMessage(msg));
			}
		}
	}

	// 重置副本
	private void resetTreasure(final int mapid) {

		for (final Object obj : L1World.getInstance()
				.getVisibleObjects((short) mapid).values()) {

			// 門關閉
			if (obj instanceof L1DoorInstance) {
				final L1DoorInstance door = (L1DoorInstance) obj;
				door.close();
			}
			// 刪除副本內的怪物
			else if (obj instanceof L1NpcInstance) {
				final L1NpcInstance npc = (L1NpcInstance) obj;
				if (npc.getMaster() == null) {
					npc.deleteMe();
				}
			} else if (obj instanceof L1FieldObjectInstance) {
				final L1FieldObjectInstance field = (L1FieldObjectInstance) obj;
				field.deleteMe();
			}

		}

	}

	// 副本內死亡的玩家重新開始
	private void reStartPlayer(final L1PcInstance pc) {
		pc.stopPcDeleteTimer();

		final int[] loc = Getback.GetBack_Location(pc, true);

		pc.removeAllKnownObjects();
		pc.broadcastPacketAll(new S_RemoveObject(pc));

		pc.setCurrentHp(pc.getLevel());
		pc.set_food(40);
		pc.setDead(false);
		pc.setStatus(0);
		L1World.getInstance().moveVisibleObject(pc, loc[2]);
		pc.setX(loc[0]);
		pc.setY(loc[1]);
		pc.setMap((short) loc[2]);
		pc.sendPackets(new S_MapID(pc.getMapId(), pc.getMap().isUnderwater()));
		pc.broadcastPacketAll(new S_OtherCharPacks(pc));
		pc.sendPackets(new S_OwnCharPack(pc));
		pc.sendPackets(new S_CharVisualUpdate(pc));
		pc.startHpRegeneration();
		pc.startMpRegeneration();
		pc.sendPackets(new S_Weather(L1World.getInstance().getWeather()));
		if (pc.getHellTime() > 0) {
			pc.beginHell();
		}
	}

	/** 觸發進程任務 **/
	public void StageMaster(final int type, final int time) {
		/*
		 * if(StageEnd.scheduledExecutionTime()!=0){ StageEnd.cancel(); }
		 */
		this.StageEnd = new Treasure(type, time * 1000);
		this.StageEnd.begin();
	}

	/** 傳送玩家入場 */
	private void TelePort(int[] xy) {
		int x = xy[0], y = xy[1];
		for (final L1PcInstance MsgPc : this._pcParty) {
			if (MsgPc != null) {
				L1Teleport.teleport(MsgPc, x, y, (short) this._mapid, 2, true);
				// MsgPc.sendPackets(new S_SkillIconGFX(71, _totaltime));//opqlo
				// 特殊地圖計時顯示
				if (y > xy[3]) {
					y--;
				} else {
					y = xy[1];
					x = xy[2];
				}
			}
		}
	}

}